a = 2

def foo():
    a = 3
    print(a)

foo()
print(a)
print("------分隔符------")

#使用global将a变为全局变量
a = 2

def foo():
    global a
    a = 3
    print(a)

foo()
print(a)
print("------分隔符------")

# 使用nonlocal将局部变量变为自由变量
def make_averager():
    total = 0
    count = 0
    def averager(value):
        nonlocal total, count
        total += value
        count += 1
        return total / count
    return averager

my_avg = make_averager()
print(my_avg(1))
print(my_avg(2))
print(my_avg(3))
print("------分隔符------")

# 3.默写装饰器
import time

def clock_it_deco(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} 程序执行时间为: {format(end_time - start_time, '.2f')} s")
        return result
    return wrapper

@clock_it_deco
def foo(a, b):
    count = 1
    while True:
        if count > a ** b:
            break
        count += 1

foo(10, 5)
print("-------分隔符------")

#4.使用装饰器来为斐波那契函数添加缓存
def cache_deco(func):
    a = {}
    def wrapper(*args):
        if args not in a:
            a[args] = func(*args)
        return a[args]
    return wrapper

@cache_deco
def fab(n):
    if n == 1:
        return 1
    if n == 0:
        return 0
    else:
        return fab(n - 1) + fab(n - 2)

print(fab(10))
